<template>
    <div class="user-diagram user-diagram-page">
        <el-row class="user-diagram_row user-diagram_row--filter" type="flex">
            <el-select class="filter-item" v-model="queryParameter.category" placeholder="品类" clearable>
                <el-option
                        v-for="{ value, label } in options.category"
                        :key="value"
                        :label="label"
                        :value="value">
                </el-option>
            </el-select>
            <el-select class="filter-item" v-model="queryParameter.model" placeholder="型号" clearable>
                <el-option
                        v-for="{ value, label} in options.model"
                        :key="value"
                        :label="label"
                        :value="value">
                </el-option>
            </el-select>
            <el-select class="filter-item" v-model="queryParameter.province"
                       placeholder="省"
                       @change="_getCityListByProvince" clearable>
                <el-option
                        v-for="{ value, label } in options.province"
                        :key="value"
                        :label="label"
                        :value="value">
                </el-option>
            </el-select>
            <el-select class="filter-item" v-model="queryParameter.city" placeholder="市" clearable>
                <el-option
                        v-for="{ value, label } in options.city"
                        :key="value"
                        :label="label"
                        :value="value">
                </el-option>
            </el-select>
        </el-row>
        <el-row class="user-diagram_row user-diagram_row--filter" type="flex">
            <el-radio
                    class="filter-item"
                    v-for="{label, value} in dateOption"
                    v-model="dateRange"
                    :key="value"
                    :label="value"
                    @change="handleDateChange"
                    border>
                {{label}}
            </el-radio>
            <el-date-picker
                    v-show="showDateRangePicker"
                    class="filter-item"
                    v-model="queryParameter.dateRange"
                    type="daterange"
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                    :clearable="false"
                    :value-format="dateFormat">
            </el-date-picker>
        </el-row>
        <el-row v-loading="onLoading" style="min-height: 82vh">
            <Vue2OrgTree
                    v-for="item in treeData"
                    :key="item.page_name"
                    horizontal
                    :props="{children: 'childList'}"
                    :data="item"
                    @on-node-click="handleNodeClick"
                    selectedKey="0"
                    selectedClassName="treeSelect"
                    :renderContent="renderContent"
            />
        </el-row>
    </div>
</template>

<script>
import _ from 'lodash'
import moment from 'moment'
import Vue2OrgTree from 'vue2-org-tree'
import { getCategory, getSN8List, getProvinceList, getCityListByProvince } from '@/utils/getSeletorData'
import commonMixin from '@/mixins/common'
import { dateFormat, dateFormatMonent } from '@/utils/consts'

export default {
  name: 'BrowseDiagram',
  components: { Vue2OrgTree },
  mixins: [commonMixin],
  data () {
    return {
      dateFormat,
      options: {
        category: getCategory(),
        model: [],
        province: [],
        city: []
      },
      queryParameter: {
        category: '',
        model: '',
        province: '',
        city: '',
        dateRange: null
      },
      dateOption: [
        {
          label: '当天',
          value: '1'
        },
        {
          label: '近7天',
          value: '7'
        },
        {
          label: '近30天',
          value: '30'
        },
        {
          label: '自定义',
          value: 'custom'
        }
      ],
      dateRange: '7',
      data: {
        id: '0',
        label: 'XXX科技有限公司',
        children: [
          {
            id: 2,
            label: '产品研发部',
            children: [
              {
                id: 5,
                label: '研发-前端'
              },
              {
                id: 6,
                label: '研发-后端'
              },
              {
                id: 9,
                label: 'UI设计'
              },
              {
                id: 10,
                label: '产品经理'
              }
            ]
          },
          {
            id: 3,
            label: '销售部',
            children: [
              {
                id: 7,
                label: '销售一部'
              },
              {
                id: 8,
                label: '销售二部'
              }
            ]
          },
          {
            id: 4,
            label: '财务部'
          },
          {
            id: 9,
            label: 'HR人事'
          }
        ]
      },
      treeData: [],
      onLoading: true,
      params: {},
      debounceGetAllTreeData: _.debounce(this._getAllTreeData, 1000, { leading: true })
    }
  },
  computed: {
    showDateRangePicker () {
      return this.dateRange === _.last(this.dateOption).value
    }
  },
  watch: {
    queryParameter: {
      handler () {
        this.debounceGetAllTreeData()
      },
      deep: true
    }
  },
  created () {
    this.init()
  },
  methods: {
    init () {
      this._getSN8List()
      this._getProvinceList()
      this.handleDateChange() // queryParameter watcher 入口
    },
    async _getSN8List () {
      const opt = await getSN8List.bind(this)()
      this.options.model = opt
    },
    async _getProvinceList () {
      this.options.province = await getProvinceList.bind(this)()
    },
    async _getCityListByProvince () {
      this.options.city = await getCityListByProvince.bind(this)()
    },
    async _getTreeData1 () {
      const { data: { data, code } } = await this.$http
        .get(this.getApiUrl('/dataanalysis_iot/userbrowse/getIndexCateMemoryPage', false),
          {
            params: this.params
          })
      if (code === 0) {
        this.treeData.push(data)
      }
    },
    async _getTreeData2 () {
      const { data: { data, code } } = await this.$http
        .get(this.getApiUrl('/dataanalysis_iot/userbrowse/getIndexDevicePagePage', false),
          {
            params: this.params
          })
      if (code === 0) {
        this.treeData.push(data)
      }
    },
    async _getTreeData3 () {
      const { data: { data, code } } = await this.$http
        .get(this.getApiUrl('/dataanalysis_iot/userbrowse/getIndexPageMenuPage', false),
          {
            params: this.params
          })
      if (code === 0) {
        this.treeData.push(data)
      }
    },
    async _getTreeData4 () {
      const { data: { data, code } } = await this.$http
        .get(this.getApiUrl('/dataanalysis_iot/userbrowse/getMenuDetailPage', false),
          {
            params: this.params
          })
      if (code === 0) {
        this.treeData.push(data)
      }
    },
    async _getAllTreeData () {
      this.onLoading = true
      this.setQueryParams()
      console.count()
      this.treeData = []
      await Promise.allSettled([this._getTreeData1()],
        this._getTreeData2(),
        this._getTreeData3(),
        this._getTreeData4())
      this.onLoading = false
    },
    setQueryParams () {
      const { category, model, province, city, dateRange } = this.queryParameter
      this.params = {
        province_name: province,
        city_name: city,
        apptype: category,
        sn8: model,
        start_day: (dateRange && dateRange[0]) || undefined,
        end_day: (dateRange && dateRange[1]) || undefined
      }
    },
    handleDateChange () {
      switch (this.dateRange) {
        case '':
          this.queryParameter.dateRange = null
          break
        case '1':
          this.queryParameter.dateRange = [moment(new Date()).format(dateFormatMonent), moment(new Date()).format(dateFormatMonent)]
          break
        case '7':
          this.queryParameter.dateRange = [moment().add('-7', 'days').format(dateFormatMonent), moment(new Date()).format(dateFormatMonent)]
          break
        case '30':
          this.queryParameter.dateRange = [moment().add('-30', 'days').format(dateFormatMonent), moment(new Date()).format(dateFormatMonent)]
          break
        default:
          break
      }
    },
    handleNodeClick (e) {
      let target = e.target
      while (!target.classList.contains('org-tree-node-label-inner')) {
        target = target.parentElement
      }
      target.classList.toggle('is-active')
    },
    renderContent (h, { name, pv, uv }) {
      return h('div',
        {
          class: 'node-content-wrap'
        }, [
          h('p', {
            class: 'content-title'
          }, name),
          h('ul', [
            h('li', {
              class: 'content-li'
            }, `PV: ${pv}`),
            h('li', {
              class: 'content-li'
            }, `UV: ${uv}`)
          ])
        ])
    }
  }
}
</script>

<style lang="scss" scoped>
    @import "~element-theme-chalk/src/common/var.scss";
    @import "@/assets/scss/modules/variables-module.scss";
    @import "@/assets/scss/modules/common-module.scss";

    .user-diagram-page {

        .user-diagram_row {
            & ~ .user-diagram_row {
                margin-top: $gap-big;
            }

            .box-card {
                & + .box-card {
                    margin-top: 0;
                    margin-left: $gap-default;
                }

                .title {
                    font-weight: bolder;
                    font-size: 145%;
                }
            }
        }

        .user-diagram_row--filter {
            @include filter-row;
        }
    }

    .chart-wrap {
        width: 100%;
        height: 100%;
    }

    ::v-deep {
        @import "~vue2-org-tree/dist/style.css";

        .org-tree-container {
            width: 100%;
            background-color: transparent;
            font-weight: bold;

            & + .org-tree-container {
                margin-top: $gap-default;
            }

            .org-tree-node-label-inner {
                padding: $gap-default;
                cursor: pointer;
                border: solid 1px #DDE4EB;
                border-radius: 5px;
                background-color: $--color-white;

                &.is-active {
                    color: white;
                    background-color: #5768F3;
                }
            }

            .node-content-wrap {
                text-align: left;

                & > ul {
                    padding-left: 1em;
                    margin-bottom: 0;
                    line-height: 1.4;
                }

                .content-title {
                    margin-top: 0;
                }
            }
        }

        .horizontal {
            $border-color: #C6C8D5;

            .org-tree-node-children::before, .org-tree-node::before, .org-tree-node::after {
                border-color: $border-color !important;
            }

            .org-tree-node:first-child::after {
                border-top-left-radius: 5px;
            }

            .org-tree-node:not(:only-child):last-child::before {
                border-bottom-left-radius: 5px;
            }

            .org-tree-node:not(:only-child):last-child:after {
                border: none;
            }

            .org-tree-node:not(:only-child):last-child:before {
                border-bottom: 1px solid $border-color;
            }
        }
    }
</style>
